<template>
  <el-dialog
    v-model="visible"
    title="分享文件"
    width="500px"
    @close="resetForm"
  >
    <div v-if="!shareResult">
      <!-- 分享设置表单 -->
      <el-form :model="shareForm" label-width="100px">
        <el-form-item label="文件名">
          <span>{{ fileInfo.filename }}</span>
        </el-form-item>
        
        <el-form-item label="分享密码">
          <el-input
            v-model="shareForm.password"
            placeholder="留空表示无密码访问"
            maxlength="20"
            show-word-limit
          />
          <div class="form-tip">设置密码可以保护您的分享文件</div>
        </el-form-item>
        
        <el-form-item label="有效期">
          <el-select v-model="shareForm.expireHours" placeholder="请选择有效期">
            <el-option label="永久有效" :value="null" />
            <el-option label="1小时" :value="1" />
            <el-option label="24小时" :value="24" />
            <el-option label="7天" :value="168" />
            <el-option label="30天" :value="720" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="访问限制">
          <el-input-number
            v-model="shareForm.maxAccessCount"
            :min="1"
            :max="1000"
            placeholder="不限制"
          />
          <div class="form-tip">限制分享链接的最大访问次数</div>
        </el-form-item>
      </el-form>
    </div>
    
    <div v-else class="share-result">
      <!-- 分享结果 -->
      <el-alert
        title="分享创建成功！"
        type="success"
        :closable="false"
        show-icon
      />
      
      <div class="share-info">
        <div class="share-item">
          <label>分享链接：</label>
          <div class="share-link">
            <el-input
              v-model="shareLink"
              readonly
              class="link-input"
            />
            <el-button type="primary" @click="copyLink">复制链接</el-button>
          </div>
        </div>
        
        <div class="share-item" v-if="shareResult.share_password">
          <label>访问密码：</label>
          <span class="password">{{ shareResult.share_password }}</span>
          <el-button type="text" @click="copyPassword">复制密码</el-button>
        </div>
        
        <div class="share-item">
          <label>分享码：</label>
          <span class="share-code">{{ shareResult.share_code }}</span>
        </div>
        
        <div class="share-item" v-if="shareResult.expire_time">
          <label>有效期至：</label>
          <span>{{ formatDate(shareResult.expire_time) }}</span>
        </div>
        
        <div class="share-item" v-if="shareResult.max_access_count">
          <label>访问限制：</label>
          <span>最多 {{ shareResult.max_access_count }} 次</span>
        </div>
      </div>
      
      <!-- 二维码 -->
      <div class="qr-code" v-if="qrCodeUrl">
        <label>扫码访问：</label>
        <img :src="qrCodeUrl" alt="分享二维码" />
      </div>
    </div>
    
    <template #footer>
      <div v-if="!shareResult">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="createShare" :loading="loading">
          创建分享
        </el-button>
      </div>
      <div v-else>
        <el-button @click="visible = false">关闭</el-button>
        <el-button type="primary" @click="resetForm">再次分享</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { createShareApi } from '@/utils/api';

const props = defineProps({
  modelValue: Boolean,
  fileInfo: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:modelValue', 'success']);

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

const shareForm = ref({
  password: '',
  expireHours: null,
  maxAccessCount: null
});

const shareResult = ref(null);
const loading = ref(false);

const shareLink = computed(() => {
  if (!shareResult.value) return '';
  const baseUrl = window.location.origin;
  return `${baseUrl}/#/share/${shareResult.value.share_code}`;
});

const qrCodeUrl = computed(() => {
  if (!shareLink.value) return '';
  // 使用在线二维码生成服务
  return `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(shareLink.value)}`;
});

const createShare = async () => {
  loading.value = true;
  try {
    const params = {
      fileId: props.fileInfo.id,
      sharePassword: shareForm.value.password || null,
      expireHours: shareForm.value.expireHours,
      maxAccessCount: shareForm.value.maxAccessCount
    };
    
    const response = await createShareApi(params);
    if (response.code === 200) {
      shareResult.value = response.data;
      ElMessage.success('分享创建成功！');
      emit('success');
    } else {
      ElMessage.error(response.msg || '分享创建失败');
    }
  } catch (error) {
    console.error('创建分享失败:', error);
    ElMessage.error('分享创建失败，请重试');
  } finally {
    loading.value = false;
  }
};

const copyLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value);
    ElMessage.success('链接已复制到剪贴板');
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea');
    textArea.value = shareLink.value;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    ElMessage.success('链接已复制到剪贴板');
  }
};

const copyPassword = async () => {
  try {
    await navigator.clipboard.writeText(shareResult.value.share_password);
    ElMessage.success('密码已复制到剪贴板');
  } catch (error) {
    ElMessage.error('复制失败，请手动复制');
  }
};

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN');
};

const resetForm = () => {
  shareForm.value = {
    password: '',
    expireHours: null,
    maxAccessCount: null
  };
  shareResult.value = null;
};

// 监听对话框关闭
watch(visible, (newVal) => {
  if (!newVal) {
    resetForm();
  }
});
</script>

<style lang="less" scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.share-result {
  .el-alert {
    margin-bottom: 20px;
  }
}

.share-info {
  margin: 20px 0;
  
  .share-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    label {
      width: 80px;
      font-weight: 500;
      color: #303133;
    }
    
    .share-link {
      display: flex;
      flex: 1;
      gap: 10px;
      
      .link-input {
        flex: 1;
      }
    }
    
    .password {
      font-family: monospace;
      background: #f5f7fa;
      padding: 4px 8px;
      border-radius: 4px;
      margin-right: 10px;
    }
    
    .share-code {
      font-family: monospace;
      font-weight: bold;
      color: #409eff;
    }
  }
}

.qr-code {
  text-align: center;
  margin-top: 20px;
  
  label {
    display: block;
    margin-bottom: 10px;
    font-weight: 500;
  }
  
  img {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
}
</style>
